package com.technology.xml;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOMParserUsing {

	private static Note note = new Note();
	
	public static void main(String[] args) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setIgnoringElementContentWhitespace(true);
		DocumentBuilder builder;
		try {
			builder = factory.newDocumentBuilder();
			
			Document doc = builder.parse("src/com/technology/xml/note.xml");
			Element rootElement = doc.getDocumentElement();
			String noteDate = rootElement.getAttribute("date");
			note.setNoteDate(new SimpleDateFormat("dd.MM.yyyy").parse(noteDate));
			NodeList nodes = rootElement.getChildNodes();
			for (int i = 0; i < nodes.getLength(); i++){
				Node tag = nodes.item(i);
				if (tag instanceof Element){
					String value = ((Element) tag).getTextContent();;
					
					switch(tag.getNodeName()){
						case "to" : note.setRecipient(value); break;
						case "from" : note.setSender(value); break;
						case "heading" : note.setSubject(value); break;
						case "body" : note.setText(value); break;
					}
					
				}
			}
			
			System.out.println("Sender :" + note.getSender());
			System.out.println("Recipient :" + note.getRecipient());
			System.out.println("Subject :" + note.getSubject());
			System.out.println("Body :" + note.getText());
			System.out.println("Note Date :" + note.getNoteDate());
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
